package edu.vital.energy.longevity.ch11.web.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;

import edu.vital.energy.longevity.ch11.model.ResponseData.ArticleResponseData;
import edu.vital.energy.longevity.ch11.model.ResponseData.StaticticsBo;
import edu.vital.energy.longevity.ch11.model.domain.Article;
import edu.vital.energy.longevity.ch11.model.domain.Category;
import edu.vital.energy.longevity.ch11.model.domain.Comment;
import edu.vital.energy.longevity.ch11.service.IArticleService;
import edu.vital.energy.longevity.ch11.service.ICommentService;
import edu.vital.energy.longevity.ch11.service.ISiteService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private ISiteService siteServiceImpl;
    @Autowired
    private IArticleService articleServiceImpl;


    @Autowired
    private ICommentService commentServcieImpl;

    @Autowired
    private edu.vital.energy.longevity.ch11.service.ICategoryService categoryServiceImpl;

    // 管理中心起始页
    @GetMapping(value = {"", "/index"})
    public String index(HttpServletRequest request) {
        // 获取最新的5篇博客、评论以及统计数据
        List<Article> articles = siteServiceImpl.recentArticles(5);
        List<Comment> comments = siteServiceImpl.recentComments(5);
        StaticticsBo staticticsBo = siteServiceImpl.getStatistics();
        // 向Request域中存储数据
        request.setAttribute("comments", comments);
        request.setAttribute("articles", articles);
        request.setAttribute("statistics", staticticsBo);
        return "back/index";
    }

    // 向文章发表页面跳转
    @GetMapping(value = "/article/toEditPage")
    public String newArticle( ) {
        return "back/article_edit";
    }
    // 发表文章
    @PostMapping(value = "/article/publish")
    @ResponseBody
    public ArticleResponseData publishArticle(Article article) {
        if (StringUtils.isBlank(article.getCategories())) {
            article.setCategories("默认分类");
        }
        try {
            articleServiceImpl.publish(article);
            logger.info("文章发布成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章发布失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }
    // 跳转到后台文章列表页面
    @GetMapping(value = "/article")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count,
                        HttpServletRequest request) {
        PageInfo<Article> pageInfo = articleServiceImpl.selectArticleWithPage(page, count);
        request.setAttribute("articles", pageInfo);
        return "back/article_list";
    }

    // 向文章修改页面跳转
    @GetMapping(value = "/article/{id}")
    public String editArticle(@PathVariable("id") String id, HttpServletRequest request) {
        Article article = articleServiceImpl.selectArticleWithId(Integer.parseInt(id));
        request.setAttribute("contents", article);
        request.setAttribute("categories", article.getCategories());
        return "back/article_edit";
    }

    // 文章修改处理
    @PostMapping(value = "/article/modify")
    @ResponseBody
    public ArticleResponseData modifyArticle(Article article) {
        try {
            articleServiceImpl.updateArticleWithId(article);
            logger.info("文章更新成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章更新失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 文章删除
    @PostMapping(value = "/article/delete")
    @ResponseBody
    public ArticleResponseData delete(@RequestParam int id) {
        try {
            articleServiceImpl.deleteArticleWithId(id);
            logger.info("文章删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章删除失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }

    }
    // 1添加评论管理页面跳转方法  url地址为 /admin/comments
//    @？？？()
//    public String  (
//        @RequestParam(defaultValue = "1") int page,
//        @RequestParam(defaultValue = "10") int count,
//        HttpServletRequest request) {
//
//        PageInfo<Comment> pageInfo =？？;
//        request.setAttribute("comments"？？
//        return ？？？？;
//    }

    // 跳转到评论编辑页面
//    @GetMapping("/comment/{id}/edit")
//    public String toEditComment(@PathVariable("id") Integer id, HttpServletRequest request) {
//        Comment comment = ?? //调用 commentServcieImpl完成更新功能;
//        request.setAttribute("comment", ???);
//        return "？？？ // 返回到 comment_edit.html 页面
//    }

    // 处理评论更新
//    @？？("？？")
//    @ResponseBody
//    public ArticleResponseData (Comment comment) {
//        try {
//            commentServcieImpl.？？？;
//            logger.info("评论更新成功");
//            return ArticleResponseData.ok();
//        } catch (Exception e) {
//            logger.error("评论更新失败，错误信息: " + e.getMessage());
//            return ArticleResponseData.fail();
//        }
//    }

    // 处理评论删除
//    @P？？("/comment/delete")
//    @ResponseBody
//    public ArticleResponseData deleteComment(@RequestParam Integer id) {
//        try {
//           //调用 删除评论方法;
//            logger.info("评论删除成功");
//            return ArticleResponseData.ok();
//        } catch (Exception e) {
//            logger.error("评论删除失败，错误信息: " + e.getMessage());
//            return ArticleResponseData.fail();
//        }
//    }

    // 分类管理
    @GetMapping("/category")
    public String categoryList(@RequestParam(value = "page", defaultValue = "1") int page,
                               @RequestParam(value = "count", defaultValue = "10") int count,
                               HttpServletRequest request) {
        PageInfo<edu.vital.energy.longevity.ch11.model.domain.Category> pageInfo = categoryServiceImpl.getAllCategories(page, count);
        request.setAttribute("categories", pageInfo);
        request.setAttribute("active", "category");
        return "back/category_list"; // 需要创建 category_list.html
    }

    // 跳转到分类添加/编辑页面 (共用一个页面)
    @GetMapping("/category/edit")
    public String toEditCategory(@RequestParam(value = "id", required = false) Integer id, HttpServletRequest request) {
        if (id != null) {
            Category category = categoryServiceImpl.getCategoryById(id);
            request.setAttribute("category", category);
        }
        request.setAttribute("active", "category");
        return "back/category_edit"; // 需要创建 category_edit.html
    }

    // 处理分类添加/更新
    @PostMapping("/category/save")
    @ResponseBody
    public ArticleResponseData saveCategory(@RequestParam(value = "id", required = false) Integer id,
                                            @RequestParam("name") String name) {
        try {
            if (StringUtils.isBlank(name)) {
                return ArticleResponseData.fail("分类名称不能为空");
            }
            if (id != null) { // 更新
                edu.vital.energy.longevity.ch11.model.domain.Category category = new edu.vital.energy.longevity.ch11.model.domain.Category();
                category.setId(id);
                category.setName(name);
                categoryServiceImpl.updateCategory(category);
                logger.info("分类更新成功: " + name);
            } else { // 添加
                categoryServiceImpl.addCategory(name);
                logger.info("分类添加成功: " + name);
            }
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("分类保存失败，错误信息: " + e.getMessage());
            return ArticleResponseData.fail("分类保存失败");
        }
    }

    // 处理分类删除
//    @PostMapping("/category/delete")
//    @ResponseBody
//    public ArticleResponseData deleteCategory(@RequestParam Integer id) {
//        try {
//            // 检查该分类下是否有文章
//            Category category = //????;
//            // 判断category是否为空  category.getCount() 是否为空   category.getCount() 并且大于0 如果有文章，则无法删除 ，
//            //if (????) {
//             //   return ArticleResponseData.fail("该分类下尚有文章，无法删除！");
//            //}
              //  调用 categoryServiceImpl删除分类方法 ,完成删除功能;
//            categoryServiceImpl？？？;
//            logger.info("分类删除成功, id: " + id);
//            return ArticleResponseData.ok();
//        } catch (Exception e) {
//            logger.error("分类删除失败，错误信息: " + e.getMessage());
//            return ArticleResponseData.fail("分类删除失败");
//        }
//    }
}

